﻿using MassTransit;
using MassTransit.RetryPolicies;
using Microsoft.EntityFrameworkCore;

namespace Orders.Api.Infrastructure
{
    public class RecreateDatabaseHostedService<TDbContext> : IHostedService where TDbContext : DbContext
    {
        private TDbContext _context;
        private readonly IServiceScopeFactory scopeFactory;
        private readonly ILogger<RecreateDatabaseHostedService<TDbContext>> logger;

        public RecreateDatabaseHostedService(IServiceScopeFactory scopeFactory, ILogger<RecreateDatabaseHostedService<TDbContext>> logger)
        {
            this.scopeFactory = scopeFactory;
            this.logger = logger;
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            logger.LogInformation("Applying migration for {DbContext}", TypeCache<TDbContext>.ShortName);

            await Retry.Interval(20, TimeSpan.FromSeconds(3)).Retry(async () =>
            {
                using var scope = scopeFactory.CreateScope();
                try
                {
                    _context = scope.ServiceProvider.GetRequiredService<TDbContext>();
                    await _context.Database.EnsureDeletedAsync();
                    await _context.Database.EnsureCreatedAsync();

                    logger.LogInformation("Migration completed for {DbContext}", TypeCache<TDbContext>.ShortName);
                }
                finally
                {
                    if (scope is IAsyncDisposable asyncDisposable)
                    {
                        await asyncDisposable.DisposeAsync();
                    }
                    else
                    {
                        scope.Dispose();
                    }
                }
            },cancellationToken);

        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
